import React from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Button, Image, ScrollView} from '@tarojs/components';
import {AtActionSheet, AtActionSheetItem, AtActivityIndicator} from 'taro-ui';

import * as T from '../../types';
import actions from '../../actions/index';
import {store2Props} from '../../selectors';
import {OSS_PATH_PREFIX, OSS_BASE_PATH_PREFIX, AVATAR_IMAGE} from '../../constant';
type IInfoProps = T.IProps & T.IInfoProps;

import PageLoading from '../../../../common/PageLoading';
import './RankingModal.less';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/flex.scss';

import classNames from 'classnames';

// @ts-ignore
@connect<Partial<IInfoProps>, T.IInfoState>(store2Props, actions)
/**
 * 游戏排行榜
 */
export default class RankingModal extends React.Component<Partial<IInfoProps>, T.IInfoState> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      ActionSheet: {
        title: '魔力豆玩家排行榜',
      },

      empty: {
        text: '大批玩家正在赶来',
      },

      pics: {
        icon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png',
        titleLeft: OSS_PATH_PREFIX + '/taskTitleLeft.png',
        titleRight: OSS_PATH_PREFIX + '/taskTitleRight.png',
        modalCloseIcon: OSS_PATH_PREFIX + '/taskModalIcon.png',
      },

      // 前三排行榜样式
      rankings: [
        {
          index: 2,
          rankingContentClassName: 'secondRankingContent',
          avatarClassName: 'secondAvatar', //头像样式
          rankingClassName: 'secondRanking', // 内容样式
        },
        {
          index: 1,
          rankingContentClassName: 'firstRankingContent',
          avatarClassName: 'firstAvatar',
          rankingClassName: 'firstRanking',
        },
        {
          index: 3,
          rankingContentClassName: 'thirdRankingContent',
          avatarClassName: 'thirdAvatar',
          rankingClassName: 'thirdRanking',
        },
      ],

      // 错误图片记录
      imageError: {},
    };
  }

  /**
   * 点击取消
   */
  handleCancel = () => {
    console.log('排行榜取消');
    this.props.onCancel();
  };

  /**
   * 渲染
   * @returns
   */
  render() {
    let {
      main: {
        status: {loadingRanking},
      },
      visible,
      actions: {action},
    } = this.props;
    const {pics, ActionSheet} = this.state;
    return (
      <AtActionSheet isOpened={visible} className="rankingModal" catchMove onClose={this.handleCancel}>
        {this.renderHeader()}
        {this.renderExtraTitle()}
        {this.renderRankingList()}
        {this.renderFooter()}
      </AtActionSheet>
    );
  }

  /**
   * 渲染头部内容
   * @returns
   */
  renderHeader() {
    const {pics, ActionSheet} = this.state;
    return (
      <View className="rankingHeader">
        <View>
          <Image src={pics.modalCloseIcon} className="rankingCloseIcon" onClick={this.handleCancel} />
          <View className="rankingTitle">{ActionSheet.title}</View>
        </View>
        {this.renderRanking()}
      </View>
    );
  }

  /**
   * 渲染排行榜（前3）
   * @returns
   */
  renderRanking() {
    const {rankings} = this.state;
    return (
      <View className={classNames('rankingTop')}>
        {rankings.map((i: any, index: number) => (
          <View className={classNames('rankingTopItem', i.rankingContentClassName)} key={'rankingTop' + index}>
            <View className={classNames('rankingTopAvatar', i.avatarClassName)}>
              <View className="rankingAvatar">
                <Image
                  src={this.handleFormatRankingInfo(i, 'headImg')}
                  className="rankingTopAvatarIcon"
                  mode="aspectFit"
                  onError={(e) =>
                    this.handleImageError(e, index, {
                      propName: 'rankingTopThreeItems',
                      imageState: 'headImg',
                    })
                  }
                />
              </View>
            </View>
            <View className={classNames('rankingTopContent', i.rankingClassName)}>
              <View className="rankingTopName">{this.handleFormatRankingInfo(i, 'nickName')}</View>
              <View className="rankingTopGrade">
                第<View className="gradeExtra">{i.index}</View>名
              </View>
              <View className="rankingTopScore">{this.handleFormatRankingInfo(i, 'magicValue')}</View>
            </View>
          </View>
        ))}
      </View>
    );
  }

  /**
   * 榜单信息
   * @returns
   */
  handleFormatRankingInfo(item, fieldName) {
    const {
      main: {rankingTopThreeItems},
    } = this.props;
    let currentItem = rankingTopThreeItems.find((i) => i.ranking == item.index);
    currentItem = currentItem || {};
    console.log('handleFormatRankingInfo currentItem', currentItem);
    let value = '';
    if (fieldName == 'headImg' && (currentItem[fieldName] == null || !currentItem[fieldName])) {
      value = AVATAR_IMAGE;
    } else if (fieldName == 'magicValue') {
      value = currentItem[fieldName] || 0;
    } else {
      value = currentItem[fieldName] || '--';
    }
    return value;
  }

  /**
   * 提示标题
   * @returns
   */
  renderExtraTitle() {
    return <View className="rankingExtraTitle">*本榜单将于自然月月底刷新</View>;
  }

  /**
   * 渲染排行版 后三
   * @returns
   */
  renderRankingList() {
    const {
      main: {rankingTopElseItems},
    } = this.props;
    return (
      <ScrollView className="rankingList" scrollY>
        {rankingTopElseItems.length > 0 ? (
          <View className="scrollContent">
            {rankingTopElseItems.map((i: any, index: number) => (
              <View key={'ranking' + index} className={classNames('rankingListItem', 'at-row')}>
                <View className="at-col at-col-2 rankingListIndex">{index + 4}</View>
                <Image
                  src={i.headImg || AVATAR_IMAGE}
                  className="at-col at-col-2 rankingListAvatar"
                  mode="aspectFit"
                  onError={(e) =>
                    this.handleImageError(e, index, {
                      propName: 'rankingTopElseItems',
                      imageState: 'headImg',
                    })
                  }
                  onLoad={() => this.handleImageLoad()}
                />
                <View className="at-col at-col-4 rankingListName">{i.nickName || '--'}</View>
                <View className="at-col at-col-4 rankingListscore">{i.magicValue || 0}</View>
              </View>
            ))}
          </View>
        ) : (
          this.renderListEmpty()
        )}
      </ScrollView>
    );
  }

  /**
   * 列表为空
   * @returns
   */
  renderListEmpty() {
    const {empty} = this.state;
    return <View className="rankingEmpty">{empty.text}</View>;
  }

  /**
   * 图片加载
   */
  handleImageLoad = () => {
    console.log('rankingModal handleImageLoad');
  };

  /**
   * 渲染底部内容
   */
  renderFooter() {
    const {
      main: {rankingSingledItems},
    } = this.props;
    let item = rankingSingledItems[0] || {};
    console.log('renderFooter singledItems=', item);
    return (
      <View className="rankingFooter at-row">
        <View className="at-col at-col-6 footerLeft">
          <View className="extraTitle">{item.ranking > 0 ? item.ranking : '暂未上榜'}</View>
        </View>
        <View className="at-col at-col-6 footerRight">
          <View className="userInfoFooter">
            <View>{item && item.nickName ? item.nickName : '--'}</View>
            <View>{item && item.magicValue ? item.magicValue : 0}</View>
          </View>
          <Image
            className="userAvatarFooter"
            src={item.headImg || AVATAR_IMAGE}
            mode="aspectFit"
            onError={(e) => this.handleFooterImageError(e)}
          />
        </View>
      </View>
    );
  }

  /**
   * 图片加载错误  通用
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    console.log('rankingModal handleImageError index', index, 'item', item);
    const {main} = this.props;
    const {propName, imageState} = item;

    let {imageError} = this.state;

    if (imageError[propName]) {
      imageError[propName] = imageError[propName].concat([index]);
    } else {
      imageError[propName] = [index];
    }

    let result = JSON.parse(JSON.stringify(main[propName]));
    console.log('rankingModal handleImageError 1111result', result);
    let currentImage = imageError[propName];
    let ids = currentImage;
    ids.map((i) => {
      console.log('rankingMdaol');
      result[i] = {
        ...result[i],
        [imageState]: AVATAR_IMAGE,
      };
    });

    console.log('rankingModal handleImageError result=', result, index);
    this.props.actions.action.commonChange('main.' + propName, result);
  };

  /**
   * 底部未上榜的用户信息（自己）
   */
  handleFooterImageError = (e) => {
    const {
      main: {rankingSingledItems},
    } = this.props;

    console.log('rankingModal handleFooterImageError singledItems', rankingSingledItems);

    let result = JSON.parse(JSON.stringify(rankingSingledItems));
    if (rankingSingledItems.length == 0) {
      result = [
        {
          headImg: AVATAR_IMAGE,
          nickName: '',
          id: '',
          magicValue: 0,
        },
      ];
    } else {
      result = rankingSingledItems;
      result[0].headImg = AVATAR_IMAGE;
    }
    this.props.actions.action.commonChange('main.rankingSingledItems', result);
  };
}
